<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import Motion from "../utils/motion";

import Token from "~icons/ri/shield-keyhole-fill";
import User from "~icons/ri/user-3-fill";

defineOptions({
  name: "TokenLogin"
});

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:loading"]);

const tokenFormRef = ref<FormInstance>();

// 动态令牌登录表单
const tokenForm = reactive({
  username: "",
  token: ""
});

// 动态令牌登录（UI演示，不实际调用API）
const onTokenLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      emit("update:loading", true);

      // 模拟登录过程
      setTimeout(() => {
        message("动态令牌登录功能仅作UI展示", { type: "info" });
        emit("update:loading", false);
      }, 1000);
    }
  });
};

defineExpose({
  tokenFormRef,
  onTokenLogin
});
</script>

<template>
  <el-form ref="tokenFormRef" :model="tokenForm" size="large">
    <Motion :delay="100">
      <el-form-item
        prop="username"
        :rules="[
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ]"
      >
        <el-input
          v-model="tokenForm.username"
          clearable
          placeholder="账号"
          :prefix-icon="useRenderIcon(User)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-form-item
        prop="token"
        :rules="[
          {
            required: true,
            message: '请输入动态令牌',
            trigger: 'blur'
          }
        ]"
      >
        <el-input
          v-model="tokenForm.token"
          clearable
          placeholder="动态令牌"
          :prefix-icon="useRenderIcon(Token)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-button
        class="login-button"
        size="large"
        type="primary"
        :loading="loading"
        :disabled="disabled"
        @click="onTokenLogin(tokenFormRef)"
      >
        登录
      </el-button>
    </Motion>
  </el-form>
</template>

<style lang="scss" scoped>
.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 6px;
}
</style>
